package org.atlantis.net.base.frame;

import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/*
 * 使用定界符区分法的成帧，解帧实现。
 */
public class DelimFramer implements Framer {

	private InputStream in;
	// 结束定界符
	private static final byte[] DELIMITER = { '}', '|' };

	public DelimFramer(InputStream in) {
		this.in = in;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.atlantis.net.base.frame.Framer#frameMessage(byte[],
	 * java.io.OutputStream)
	 */
	@Override
	public void frameMessage(byte[] message, OutputStream out)
			throws IOException {
		for (int i = 0; i < message.length; i++) {
			if (i < message.length - 1 && message[i] == DELIMITER[0]
					&& message[i + 1] == DELIMITER[1]) {
				throw new IOException("Message contains delimiter.");
			}
		}
		out.write(message);
		out.write(DELIMITER);
		out.flush();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.atlantis.net.base.frame.Framer#nextMessage()
	 */
	@Override
	public byte[] nextMessage() throws IOException {
		ByteArrayOutputStream messageBuffer = new ByteArrayOutputStream();
		int prevByte;
		int nextByte;
		while (!((prevByte = in.read()) == DELIMITER[0])
				&& ((nextByte = in.read()) == DELIMITER[1])) {
			if (nextByte == -1) { // 已经读取完
				if (messageBuffer.size() == 0) { // 但是什么都没有读取到，表示InputStream为空
					return null;
				} else { // 读取到一部分数据，表示这条信息没有结束定界符
					throw new EOFException(
							"Non-empty message without delimiter");
				}
			}
			messageBuffer.write(prevByte);
			messageBuffer.write(nextByte);
		}
		return messageBuffer.toByteArray();
	}
}
